import React, { useEffect, useRef } from 'react';
import { Card, Divider, Empty, Grid, Space, Statistic, Switch, Typography } from '@arco-design/web-react';
import instance from '@/utils/request';
import { ParameterRecord } from '@/pages/equipment/parameter';
import moment from 'moment';
import useLocale from '@/utils/useLocale';
import { resolveParameterDataType, resolveParameterValueType } from '@/constants/functions';
import { dayjs } from '@arco-design/web-react/es/_util/dayjs';
import DynamicArrow from '@/components/common/dynamic_arrow';
import { resolveColor } from '@/utils/color';
import { Axis, Chart, LineAdvance } from 'bizcharts';

const { Row, Col } = Grid;

const locale = {
  'en-US': {},
  'zh-CN': {
    'label.auto_refresh': '自动刷新',
    'title.monitor.compare': '较上次'
  }
};

const RealtimePanel = (props: {
  id: number,
  parameters: ParameterRecord[]
}) => {
  const t = useLocale(locale);
  const [data, setData] = React.useState<{
    info?: ParameterRecord,
    records?: {
      value?: string | number | null,
      time?: string,
    }[]
  } []>([]);

  const taskId = useRef<NodeJS.Timer>();

  const fetchData = async () => {
    const date = moment();
    instance
      .post('/api/device/monitor', {
        deviceId: props.id,
        parameterIds: (props.parameters || []).map(it => it.id),
        startDateTime: date.format('YYYY-MM-DD') + ' 00:00:00',
        endDateTime: date.format('YYYY-MM-DD') + ' 23:59:59',
        limit: 1,
        direction: 'DESC'
      })
      .then((res) => {
        if (res.data.code === 200) {
          setData((res.data.data?.paramInfos || []));
        } else {
          setData([]);
        }
      });
  };

  useEffect(() => {
    fetchData();
    taskId.current = setInterval(() => fetchData(), 5000);
    return () => {
      if (!!taskId.current) {
        clearInterval(taskId.current);
      }
    };
  }, []);

  return (
    <Card>
      <Row justify={'end'}>
        <Space>
          <Typography.Text>{t['label.auto_refresh']}</Typography.Text>
          <Switch defaultChecked={true} onChange={(v) => {
            !!taskId.current && clearInterval(taskId.current);
            if (!!v) {
              taskId.current = setInterval(() => fetchData(), 5000);
            }
          }}></Switch>
        </Space>
      </Row>
      <Divider />
      <Row>
        <Col span={24}>
          <Grid cols={4} colGap={12} rowGap={16}>
            {(data || []).map((item) => {
              return <Grid.GridItem key={'id_' + item.info.id}>
                <Card key={item.info.id}
                      style={{ border: '1px solid #dddddd' }}
                      title={<Typography>
                        <Typography.Text
                          style={{ fontSize: '1.2rem', fontWeight: 'bolder' }}>{item.info.name}
                        </Typography.Text>
                      </Typography>
                      }
                      extra={
                        <Space>
                          <Typography.Text style={{
                            fontSize: '.9rem',
                            color: 'grey'
                          }}>{item.info.code}
                          </Typography.Text>
                          <Typography.Text style={{
                            fontSize: '1rem',
                            color: 'grey'
                          }}> {resolveParameterValueType(item.info.valueType)} </Typography.Text>
                          <Typography.Text style={{
                            fontSize: '0.9rem',
                            color: 'grey'
                          }}>{resolveParameterDataType(item.info.dataType)}</Typography.Text>
                        </Space>
                      }
                      actions={[
                        <Typography.Text key={item.info.id + '_time'}
                                         style={{ color: 'grey' }}>{item.records.length >= 2 ? dayjs(item.records[1].time).format('YYYY-MM-DD HH:mm:ss.SSS') : ''}</Typography.Text>
                      ]}
                > {
                  item.records.length >= 2
                    ?
                    <Row>
                      <Col span={10}>
                        <Col span={24}>
                          {
                            item.records.length >= 2 &&
                            <Statistic styleValue={{
                              fontSize: '2rem',
                              color: resolveColor((item.records[0].value as number), (item.records[1].value as number))
                            }} value={item.records[0].value} countUp />
                          }
                        </Col>
                        <Col span={24}>
                          {
                            item.records.length >= 2 &&
                            <Statistic
                              styleValue={{
                                fontSize: '1.1rem',
                                color: resolveColor((item.records[0].value as number), (item.records[1].value as number))
                              }}
                              prefix={<Typography.Text
                                style={{
                                  color: 'grey',
                                  fontSize: '0.8rem'
                                }}>{t['title.monitor.compare']}</Typography.Text>}
                              countUp
                              value={(item.records[0].value as number) - (item.records[1].value as number) != 0 ? (item.records[0].value as number) - (item.records[1].value as number) : ''}
                              suffix={<DynamicArrow o1={item.records[0].value as number}
                                                    o2={item.records[1].value as number} />}
                            />
                          }
                        </Col>
                      </Col>
                      <Col span={14}>
                        {
                          item.records.length > 0 &&
                          <Chart padding={[0, 0, 0, 0]} autoFit data={[...item.records].reverse()}>
                            <Axis visible={false} />
                            <LineAdvance shape="smooth" position="time*value"></LineAdvance>
                          </Chart>
                        }
                      </Col>
                    </Row>
                    : <Empty />
                }
                </Card>
              </Grid.GridItem>;
            })}
          </Grid>
        </Col>
      </Row>
    </Card>
  );
};

export default RealtimePanel;